<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\V1\Resources\VipPurchaseResource;
use App\Services\MakeVipPurchase\MakeVipPurchase;
use App\Services\GiftVipPurchase\GiftVipPurchase;
use App\Services\GiftVipPurchase\GiftVipPurchaseRequest;
use App\Http\Controllers\Api\V1\Queries\VipCardQuery;
use App\Models\User;
use Rainsens\Dinglog\Facades\Dinglog;
class VipPurchasesController extends Controller
{
	
	public function store()
	{

		$lock = Cache::lock('buy_vip', 10);

		try {

			if (!$lock->get()) fail('处理中...请勿频繁操作');
			$vipPurchase = app(MakeVipPurchase::class, [
				'user' => request()->user(),
			])->make();
			
		} finally {
			$lock->release();
		}
		return new VipPurchaseResource($vipPurchase);
	}



	public function use()
	{


		if (Cache::lock('use_vip_card', 10)->get()) {
		    $vipPurchase = app(MakeVipPurchase::class, [
				'user' => request()->user(),
				'method' => 'card'
			])->make();
		    Cache::lock('use_vip_card')->release();//一定要在结尾处释放锁，不然会导致别的并行或后续请求一直无法获取锁而停滞

		    return new VipPurchaseResource($vipPurchase);
		}else{
			fail('处理中...请勿频繁操作');

		}
	
	}


	public function gift()
	{

		$lock = Cache::lock('gift_vip', 10);

		try {

			if (!$lock->get()) fail('处理中...请勿频繁操作');

			$request = app(GiftVipPurchaseRequest::class);

			$vipPurchase = app(GiftVipPurchase::class, [
				'self' => request()->user(),
				'guser' => $request->getGuser(),
				'cards' => request()->cards,
				
			])->apply();

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}

	public function index(VipCardQuery $query): array
	{
		$user = request()->user();
		$condition = request('condition');
		$query = $query->where('user_id', $user->id);
		$query = !empty(request('start_time')) ? $query->where('created_at', '>', request('start_time')) : $query;
		$query = !empty(request('end_time')) ? $query->where('created_at', '<', request('end_time')) : $query;
	
		$total = $query->inquire($condition)->sum('money');
		$cards = $query->inquire($condition)->orderByDesc('id')->paginate();
		foreach($cards as &$card){

			
			if($card->data){

				if(isset($card->data['gift_user_id'])){
					$user = User::find($card->data['gift_user_id']);
					
				}elseif(isset($card->data['parent_user_id'])){
					$user = User::find($card->data['parent_user_id']);
					
				}

				$card->nick_name = isset($user) ? $user->name : ''; 

			}else{
				$user = User::find($card->user_id);

				$card->nick_name = isset($user) ? $user->name : ''; 
			}
		}
		
		return ['total' => $total, 'data' => $cards];
	}
}
